package red.stu.csc.spring;

import java.util.Collection;
import java.util.Map;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import red.stu.csc.CSCServer;
import red.stu.csc.pojo.DynamicClass;

public class CSCSpringContextHolder implements ApplicationContextAware, DisposableBean {
	
	private ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		// 升级扫描器的默认new的对象
		// System.out.println("升级扫描器的默认new的对象");
		// 查询所有CSCServer Bean
		Map<String, CSCServer> cscServerBeans = applicationContext.getBeansOfType(CSCServer.class);
		// 查询所有Bean
		Map<String, Object> beans = applicationContext.getBeansOfType(Object.class);
		// 遍历所有CSCServer
		if (cscServerBeans != null && beans != null) {
			Collection<CSCServer> cscServers = cscServerBeans.values();
			for (CSCServer cscServer : cscServers) {
				// 获取所有DynamicClass
				Collection<DynamicClass> dynamicClasss = cscServer.getDynamicClassMap().values();
				for (DynamicClass dClass : dynamicClasss) {
					// 尝试从Bean中获取，并替换原始运行对象
					Object obj = applicationContext.getBean(dClass.getThisObj().getClass());
					if (obj != null)
						dClass.setThisObj(obj);
				}
			}
			
		}
	}
	
	@Override
	public void destroy() throws Exception {
		// 关闭所有CSCServer
		Map<String, CSCServer> cscServerBeans = applicationContext.getBeansOfType(CSCServer.class);
		if (cscServerBeans != null) {
			Collection<CSCServer> cscServers = cscServerBeans.values();
			for (CSCServer cscServer : cscServers)
				cscServer.stop();
		}
	}
	
}